/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package controllers

import (
	"strconv"
	"strings"

	"github.com/astaxie/beego"
	"WebAdminSys/libs"
	"WebAdminSys/models"
	"github.com/dchest/captcha"
	"time"
)

const (
	MSG_OK  = 0
	MSG_ERR = -1
)

type BaseController struct {
	beego.Controller
	controllerName string
	actionName     string
	user           *models.ManageAdminUser
	userId         int
	userName       string
	loginName      string
	pageSize       int
	allowUrl       string
	sethomedirectory string
	curOperationLogID int64 //操作日志ID
}

func (this *BaseController) VerifyCaptcha() {
	startTime := time.Now()
	captchaId := this.GetString("captchaId")
	captchaValue := this.GetString("captcha")
	if !captcha.VerifyString(captchaId, captchaValue) {
		this.Data["json"] = JsonFormat(0, "verify captcha fail", "", startTime)
	} else {
		this.Data["json"] = JsonFormat(1, "success", "", startTime)
	}
	this.ServeJSON()
}

//前期准备
func (self *BaseController) Prepare() {
	self.pageSize = 20
	controllerName, actionName := self.GetControllerAndAction()
	self.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
	self.actionName = strings.ToLower(actionName)
	self.Data["version"] = beego.AppConfig.String("version")
	self.Data["siteName"] = beego.AppConfig.String("site.name")
	self.Data["curRoute"] = self.controllerName + "." + self.actionName
	self.Data["curController"] = self.controllerName
	self.Data["curAction"] = self.actionName
	d := struct {
		CaptchaId string
	}{
		captcha.New(),
	}
	self.Data["CaptchaId"] = d.CaptchaId
	//if self.controllerName== "manageadmin" {
		//self.Ctx.WriteString("prepare :" + self.controllerName + "." + self.actionName)
	//}
	// noAuth := "ajaxsave/ajaxdel/table/loginin/loginout/getnodes/start"
	// isNoAuth := strings.Contains(noAuth, self.actionName)
	// if isNoAuth == false {
	if !self.auth(){
			self.Ctx.SetCookie(libs.GetEnCodeByMd5("auth"), "",-1)
			self.redirect(beego.URLFor("LoginController.LoginIn"))
		return
	}
	// }

	self.Data["loginUserId"] = self.userId
	self.Data["loginUserName"] = self.userName
}

//登录权限验证
func (self *BaseController) auth()  bool {

	arr := strings.Split(self.Ctx.GetCookie(libs.GetEnCodeByMd5("auth")), "|")
	self.userId = 0
	if len(arr) == 2 {
		idstr, password := arr[0], arr[1]
		userId, _ := strconv.Atoi(idstr)
		if userId > 0 {
			user, err := models.ManageAdminGetById(userId)
			if err != nil || password != libs.GetEnCodeByMd5(self.getClientIp()+"|"+user.Password+user.Salt) {
				return false
			}
			
			self.userId = user.Id
			self.loginName = user.LoginName
			self.userName = user.RealName
			self.user = user
			
			self.AdminAuth()

			isHasAuth := strings.Contains(self.allowUrl, self.controllerName+"/"+self.actionName)
		
			noAuth := "/table/loginin/loginout/start/show/"
			isNoAuth := strings.Contains(noAuth, self.actionName)
			if isHasAuth == false && isNoAuth == false {
				self.Ctx.WriteString("没有权限")
				self.ajaxMsg("没有权限", MSG_ERR)
				return false
			}
			return true
		}
	}

	if self.userId == 0 && (self.controllerName != "login" && self.actionName != "loginin") {
		self.redirect(beego.URLFor("LoginController.LoginIn"))
		return false
	}
	return true
}

func (self *BaseController) AdminAuth() {
	// 左侧导航栏
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 1)
	if self.userId != 1 {
		//普通管理员
		adminAuthIds, _ := models.ManageRoleAuthGetByIds(self.userId)
		adminAuthIdArr := strings.Split(adminAuthIds, ",")
		filters = append(filters, "id__in", adminAuthIdArr)
	}
	result, _ := models.ManageAuthGetList(1, 1000, filters...)
	list := make([]map[string]interface{}, len(result))
	list2 := make([]map[string]interface{}, len(result))
	allow_url := ""
	i, j := 0, 0
	for _, v := range result {
		if v.AuthUrl != " " || v.AuthUrl != "/" {
			allow_url += v.AuthUrl
		}
		row := make(map[string]interface{})
		if v.Pid == 1 && v.IsShow == 1 {
			row["Id"] = int(v.Id)
			row["Sort"] = v.Sort
			row["AuthName"] = v.AuthName
			row["AuthUrl"] = v.AuthUrl
			row["Icon"] = v.Icon
			row["Pid"] = int(v.Pid)
			list[i] = row
			i++
		}
		if v.Pid != 1 && v.IsShow == 1 {
			row["Id"] = int(v.Id)
			row["Sort"] = v.Sort
			row["AuthName"] = v.AuthName
			row["AuthUrl"] = v.AuthUrl
			row["Icon"] = v.Icon
			row["Pid"] = int(v.Pid)
			list2[j] = row
			j++
		}
	}

	self.Data["SideMenu1"] = list[:i]  //一级菜单
	self.Data["SideMenu2"] = list2[:j] //二级菜单

	self.allowUrl = allow_url + "/home/index"
}

// 是否POST提交
func (self *BaseController) isPost() bool {
	return self.Ctx.Request.Method == "POST"
}

//获取用户IP地址
func (self *BaseController) getClientIp() string {
	s := strings.Split(self.Ctx.Request.RemoteAddr, ":")
	return s[0]
}

// 重定向
func (self *BaseController) redirect(url string) {
	//self.Ctx.WriteString(url)
	self.Redirect(url, 302)
	self.StopRun()
}

//加载模板
func (self *BaseController) display(tpl ...string) {
	//self.Ctx.WriteString(tpl)
	var tplname string
	if len(tpl) > 0 {
		tplname = strings.Join([]string{tpl[0], "html"}, ".")
	} else if len(self.sethomedirectory) > 0{
		tplname = self.sethomedirectory + "/" + self.controllerName + "/" + self.actionName + ".html"
	}else{
		tplname = self.controllerName + "/" + self.actionName + ".html"
	}
	//self.Ctx.WriteString(tplname)
	self.Layout = "public/layout.html"
	self.TplName = tplname

}

//ajax返回
func (self *BaseController) ajaxMsg(msg interface{}, msgno int) {
	out := make(map[string]interface{})
	out["status"] = msgno
	out["message"] = msg
	self.Data["json"] = out
	self.ServeJSON()
	self.StopRun()
}

//ajax返回 列表
func (self *BaseController) ajaxList(msg interface{}, msgno int, count int64, data interface{}) {
	out := make(map[string]interface{})
	out["code"] = msgno
	out["msg"] = msg
	out["count"] = count
	out["data"] = data
	self.Data["json"] = out
	self.ServeJSON()
	self.StopRun()
}

//ajax返回 列表
func (self *BaseController) ajaxTilteList(msg interface{}, msgno int, count int64,titleinfo,data interface{}) {
	out := make(map[string]interface{})
	out["code"] = msgno
	out["msg"] = msg
	out["count"] = count
	out["titleinfo"] = titleinfo
	out["data"] = data
	self.Data["json"] = out
	self.ServeJSON()
	self.StopRun()
}

//操作日志 0 成功  其他失败
func (self *BaseController) AddOperationLog(log string, status int) {
	var nl = new(models.GMOperationLog);
	
	nl.Id = 0;
	nl.Manager_id = int64(self.userId);
	nl.Manager_name = self.userName;
	nl.Operation_time = beego.GetTimeNowString();
	nl.Operation_IP = self.getClientIp();
	nl.Explain = log;
	nl.Status = status;
	nl.Unix_time = time.Now().Unix();
	nl.Manager_account = self.loginName;
	nl.ControllerName =self.controllerName;
	nl.ActionName =self.actionName;

	models.GMOperationLogInsertValue(nl);

}



// 1 success
// 0 fail
func JsonFormat(retcode int, retmsg string, retdata interface{}, stime time.Time) (json map[string]interface{}) {
	cost := time.Now().Sub(stime).Seconds()
	if retcode == 1 {
		json = map[string]interface{}{
			"code": retcode,
			"data": retdata,
			"desc": retmsg,
			"cost": cost,
		}
	} else {
		json = map[string]interface{}{
			"code": retcode,
			"desc": retmsg,
			"cost": cost,
		}
	}

	return json
}

//验证用户点击权限
func (self *BaseController) UserAuthData( iRight int) bool {
	if self.userId == 1 {
		return true;
	}
	return models.GetUserRightByID(iRight,self.userId);
}